﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Web;
using System.Net;
using XiaoYuStock.Core.Entities;

using NPOI.XSSF.UserModel;

namespace XiaoYuStock.Core
{
    public class SharesService
    {

        /// <summary>
        /// 上交所地址
        /// http://www.sse.com.cn/assortment/stock/list/share/
        /// </summary>
        private static string SH_SHARES_URL = "http://www.sse.com.cn/assortment/stock/list/share/";

        /// <summary>
        /// 
        /// </summary>
        private static string SH_SHARES__EXCEL_URL = "http://query.sse.com.cn/security/stock/downloadStockListFile.do?csrcCode=&stockCode=&areaName=&stockType=1";


        /// <summary>
        /// http://www.szse.cn/main/marketdata/jypz/colist/
        /// 
        /// </summary>
        private static string SZ_SHARES_EXCEL_ALL_URL = "http://www.szse.cn/szseWeb/ShowReport.szse?SHOWTYPE=xlsx&CATALOGID=1110&tab1PAGENUM=1&ENCODE=1&TABKEY=tab1";

        /// <summary>
        /// A股
        /// </summary>
        private static string SZ_SHARES_EXCEL_A_URL = "http://www.szse.cn/api/report/ShowReport?SHOWTYPE=xlsx&CATALOGID=1110&TABKEY=tab1&random=0.8824306745359083";
        /// <summary>
        /// B股
        /// </summary>
        private static string SZ_SHARES_EXCEL_S_URL = "http://www.szse.cn/api/report/ShowReport?SHOWTYPE=xlsx&CATALOGID=1110&TABKEY=tab2&random=0.10923431803642991";
        /// <summary>
        /// A+B股
        /// </summary>
        private static string SZ_SHARES_EXCEL_M_URL = "http://www.szse.cn/api/report/ShowReport?SHOWTYPE=xlsx&CATALOGID=1110&TABKEY=tab4&random=0.901420717207787";

        public List<ShareData> GetSHData()
        {
            List<ShareData> list = new List<ShareData>();
            string file = "tmpExcel.cvs";
            string stmp = System.Reflection.Assembly.GetExecutingAssembly().Location;
            string filePath = Path.Combine(stmp.Substring(0, stmp.LastIndexOf('\\')), "temp", file);
            if (HttpContext.Current != null)
            {
                filePath = HttpContext.Current.Server.MapPath("~/temp/" + file);
            }

            if (File.Exists(filePath))
            {
                File.Delete(filePath);
            }
            RequestHelp.DownLoadFile2(SH_SHARES_URL, SH_SHARES__EXCEL_URL, filePath);
            try
            {

                using (FileStream fs = File.OpenRead(filePath))
                {
                    StreamReader sr = new StreamReader(fs, Encoding.GetEncoding("GB2312"));

                    string strLine = "";
                    string[] cells = null;
                    int index = 0;

                    while ((strLine = sr.ReadLine()) != null)
                    {
                        index++;
                        if (index == 1)
                            continue;
                        cells = strLine.Split('\t');
                        var currentDateTime = DateTime.Now;
                        var currentTotalCapital = 0m;
                        var currentCirculateCapital = 0m;
                        //创建列
                        ShareData item = new ShareData();
                        item.ShareCode = cells[2].Trim();
                        item.ShareName = cells[3].Trim();

                        DateTime.TryParse(cells[4].Trim(), out currentDateTime);
                        item.MarketDate = currentDateTime;

                        if (cells.Length > 5)
                        {
                            Decimal.TryParse(cells[5].ToString(), out currentTotalCapital);
                            item.TotalCapital = currentTotalCapital;
                        }

                        if (cells.Length > 6)
                        {
                            Decimal.TryParse(cells[6].ToString(), out currentCirculateCapital);
                            item.CirculateCapital = currentCirculateCapital;
                        }
                        list.Add(item);


                    }
                    sr.Close();
                }
            }
            catch (Exception ex)
            {
            }

            return list;
        }

        private List<ShareData> GetSZData(string url)
        {
            List<ShareData> list = new List<ShareData>();
            string file = "tmpExcel.cvs";
            string stmp = System.Reflection.Assembly.GetExecutingAssembly().Location;
            string filePath = Path.Combine(stmp.Substring(0, stmp.LastIndexOf('\\')), "temp", file);
            if (HttpContext.Current != null)
            {
                filePath = HttpContext.Current.Server.MapPath("~/temp/" + file);
            }

            if (File.Exists(filePath))
            {
                File.Delete(filePath);
            }
            RequestHelp.DownLoadFile(url, filePath);
            try
            {
                using (FileStream fs = File.OpenRead(filePath))
                {
                    XSSFWorkbook workbook = new XSSFWorkbook(fs);

                    var sheet = workbook.GetSheetAt(0);

                    for (int i = 1; i < sheet.LastRowNum; i++)
                    {
                        var row = sheet.GetRow(i);
                        ShareData item = new ShareData();
                        item.ShareCode = row.GetCell(4).ToString().Trim();
                        item.ShareName = row.GetCell(5).ToString().Trim();
                        item.MarketDate = Convert.ToDateTime(row.GetCell(6).ToString().Trim());
                        item.TotalCapital = Convert.ToDecimal(row.GetCell(7).ToString().Trim());
                        item.CirculateCapital = Convert.ToDecimal(row.GetCell(8).ToString().Trim());
                        string category = row.GetCell(17).ToString().Trim();
                        item.CategoryCode = category.Substring(0, 1);//18
                        item.CategoryName = category.Substring(1);//18
                        item.Url = row.GetCell(18).ToString().Trim();
                        list.Add(item);
                    }

                }
            }
            catch (Exception ex)
            {
            }

            return list;
        }


        public List<ShareData> GetSZDataA()
        {
            return this.GetSZData(SZ_SHARES_EXCEL_A_URL);
        }

        public List<ShareData> GetSZDataS()
        {
            return this.GetSZData(SZ_SHARES_EXCEL_S_URL);
        }

        public List<ShareData> GetSZDataM()
        {
            return this.GetSZData(SZ_SHARES_EXCEL_M_URL);
        }
    }



}
